//
//  LGCycleScrollView.m
//  InfiniteLoop
//
//  Created by 徐冉 on 2018/12/13.
//  Copyright © 2018年 LG. All rights reserved.
//

#import "LGCycleScrollView.h"
#import <SDCycleScrollView/TAPageControl.h>

@interface SDCycleScrollView ()
#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView;

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;

- (instancetype)initWithFrame:(CGRect)frame;

- (void)awakeFromNib;

@property (nonatomic, weak) UIControl *pageControl;

@end

@interface LGCycleScrollView()



@end

@implementation LGCycleScrollView


- (UIControl *)pageControl {
    return [super pageControl];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.lastOffset = CGPointMake(56250.0, 0);
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    self.lastOffset = CGPointMake(56250.0, 0);
}

#pragma mark - UIScrollViewDelegate

//scrollView滚动时，就调用该方法。任何offset值改变都调用该方法。即滚动过程中，调用多次
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [super scrollViewDidScroll:scrollView];

    if (scrollView.contentOffset.x > _lastOffset.x) {//向左
        self.direction = LGCycleScrollViewDirectionLeft;
    }else {//向右
        self.direction = LGCycleScrollViewDirectionRight;
    }

    if ([self.pageControl isKindOfClass:[TAPageControl class]]) {
        TAPageControl *pageControl = (TAPageControl *)self.pageControl;
        self.curIndex = pageControl.currentPage;
    } else {
        UIPageControl *pageControl = (UIPageControl *)self.pageControl;
        self.curIndex = pageControl.currentPage;
    }
    
    if (_scrollViewDidScrollBlock != nil) {
        _scrollViewDidScrollBlock(scrollView);
    }

//    NSLog(@"direction:%@",self.direction == LGCycleScrollViewDirectionLeft ? @"left" : @"right");
//    NSLog(@"curIndex:%ld",self.curIndex);
//    NSLog(@"%.f",scrollView.contentOffset.x - self.lastOffset.x);
}

// 当滚动视图动画完成后，调用该方法，如果没有动画，那么该方法将不被调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [super scrollViewDidEndScrollingAnimation:scrollView];
    __weak __typeof(self) weakself= self;
    dispatch_async(dispatch_get_main_queue(), ^{
        weakself.lastOffset = scrollView.contentOffset;
    });
    if (_scrollViewDidEndScrollBlock != nil) {
        _scrollViewDidEndScrollBlock(scrollView);
    }
    
}


@end
